package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private String[] usernameArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();

    }
    //视图
    public void initView(){
        listView = findViewById(R.id.listview);
    }
    //数据
    public void initData(){
        usernameArray = new String[]{"周子豪","周明","杨磊","杨玉龙"};
        listView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return usernameArray.length;
            }
            //返回数据集中指定位置的数据对象
            @Override
            public Object getItem(int position) {
                return usernameArray[position];
            }
//返回数据集中指定位置的数据的ID
            @Override
            public long getItemId(int position) {
                return position;
            }
//将指定位置的数据构成一个可以显示在AdapterView中的组件，并返回AdapterView
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView ==null){
                    convertView = View.inflate(MainActivity.this,R.layout.listview_item_layout,null);
                }
                TextView usernameTV = convertView.findViewById(R.id.username_tv);
                usernameTV.setText(usernameArray[position]+"");
                return convertView;
            }
        });
    }
    //事件监听
    public void initEvent(){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //点击跳转到TwoActivity[数据展示信息学院20级专业班级]
        Intent intent = new Intent(MainActivity.this,TwoActivity.class);
        startActivity(intent);
        Toast.makeText(MainActivity.this,usernameArray[position]+"", Toast.LENGTH_SHORT).show();
    }
});
    }
}